﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Base64
{
    /// <summary>
    /// Encode a binary file to base64 string.
    /// </summary>
    /// <datetime>04/10/2012-11:07</datetime>
    class Encode64
    {

        /// <summary>
        /// Encodes the file to base64. Using memory methode. Suitable for small size file.
        /// </summary>
        /// <param name="FileToEncode">The file to encode.</param>
        /// <returns>The encoded string</returns>
        /// <datetime>04/10/2012-11:03</datetime>
        public static string EncodeFileToBase64_Mem(string FileToEncode) // Encode small file
        {
            byte[] b_data = File.ReadAllBytes(FileToEncode);
            string EncodedString = System.Convert.ToBase64String(b_data);

            return EncodedString;
        }

        /// <summary>
        /// Encodes the file to base64.
        /// </summary>
        /// <param name="FileToEncode">The file to encode.</param>
        /// <returns>The encoded string</returns>
        /// <datetime>04/10/2012-11:05</datetime>
        public static string EncodeFileToBase64(string FileToEncode) // Encode a large file
        {
            string EncodedString = "";

            int BASE64_BLOCK_SIZE = 3*1024; // Need to devided by 3
            byte[] buffer = new byte[BASE64_BLOCK_SIZE];
            int bytesRead;

            try
            {
                // Open file for reading
                System.IO.FileStream _FileStream = new System.IO.FileStream(FileToEncode, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                while ((bytesRead = _FileStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    EncodedString = EncodedString + System.Convert.ToBase64String(buffer, 0, bytesRead);
                }

                // close file stream
                _FileStream.Close();
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }

            return EncodedString;
        }

        /// <summary>
        /// Writes the encoded to file.
        /// </summary>
        /// <param name="EncodedString">The encoded string.</param>
        /// <param name="outputFile">The output file.</param>
        /// <datetime>04/10/2012-11:06</datetime>
        public static void WriteEncodedToFile(string EncodedString, string outputFile)
        {
            StreamWriter sw_dest = new StreamWriter(outputFile);
            sw_dest.Write(EncodedString);
            sw_dest.Flush();
            sw_dest.Close();
        }

    }
}
